﻿Imports System.Data.OleDb
Imports System.IO
Imports System.Net.NetworkInformation

Public Class storecontrol
#Region "SQL"
    Function Add() As Boolean
        Try
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource


            command.CommandText = "INSERT INTO [dbo].[stores] ([company],[storenumber],[storename],[gateway],[serverip],[mws],[biometrics],[pos1],[pos2],[pos3],[pos4],[status],[type_],[provider])  " & _
                                                     "VALUES (@company, @storenumber, @storename, @gateway,@serverip,@mws,@biometrics,@pos1,@pos2,@pos3,@pos4,@status,@type_,@provider)"

            command.Parameters.Add("@company", SqlDbType.NVarChar)
            command.Parameters.Add("@storenumber", SqlDbType.NVarChar)
            command.Parameters.Add("@storename", SqlDbType.NVarChar)
            command.Parameters.Add("@gateway", SqlDbType.NVarChar)
            command.Parameters.Add("@serverip", SqlDbType.NVarChar)
            command.Parameters.Add("@mws", SqlDbType.NVarChar)
            command.Parameters.Add("@biometrics", SqlDbType.NVarChar)
            command.Parameters.Add("@pos1", SqlDbType.NVarChar)
            command.Parameters.Add("@pos2", SqlDbType.NVarChar)
            command.Parameters.Add("@pos3", SqlDbType.NVarChar)
            command.Parameters.Add("@pos4", SqlDbType.NVarChar)
            command.Parameters.Add("@status", SqlDbType.NVarChar)
            command.Parameters.Add("@type_", SqlDbType.NVarChar)
            command.Parameters.Add("@provider", SqlDbType.NVarChar)
            connection.Open()
            command.Connection = connection

            command.Parameters("@company").Value = company
            command.Parameters("@storenumber").Value = txtStoreno.Text
            command.Parameters("@storename").Value = txtStorename.Text
            command.Parameters("@gateway").Value = txtgateway.Text
            command.Parameters("@serverip").Value = txtserver.Text
            command.Parameters("@mws").Value = txtmws.Text
            command.Parameters("@biometrics").Value = txtbio.Text
            command.Parameters("@pos1").Value = txtpos1.Text
            command.Parameters("@pos2").Value = txtpos2.Text
            command.Parameters("@pos3").Value = txtpos3.Text
            command.Parameters("@pos4").Value = ""
            command.Parameters("@status").Value = ""
            command.Parameters("@type_").Value = Type
            command.Parameters("@provider").Value = txtprovider.Text
            command.ExecuteNonQuery()

            Clear()
            Try
                LoadStores()
            Catch ex As Exception
            End Try
            Return True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Function Edit(key As String) As Boolean
        Try
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource


            command.CommandText = "UPDATE [dbo].[stores] SET [company]=@company,[storenumber]=@storenumber,[storename]=@storename,[gateway]=@gateway,[serverip]=@serverip,[mws]=@mws,[biometrics]=@biometrics,[pos1]=@pos1,[pos2]=@pos2,[pos3]=@pos3,[pos4]=@pos4,[status]=@status,[type_]=@type_,[provider]=@provider WHERE p_key=" & key

            command.Parameters.Add("@company", SqlDbType.NVarChar)
            command.Parameters.Add("@storenumber", SqlDbType.NVarChar)
            command.Parameters.Add("@storename", SqlDbType.NVarChar)
            command.Parameters.Add("@gateway", SqlDbType.NVarChar)
            command.Parameters.Add("@serverip", SqlDbType.NVarChar)
            command.Parameters.Add("@mws", SqlDbType.NVarChar)
            command.Parameters.Add("@biometrics", SqlDbType.NVarChar)
            command.Parameters.Add("@pos1", SqlDbType.NVarChar)
            command.Parameters.Add("@pos2", SqlDbType.NVarChar)
            command.Parameters.Add("@pos3", SqlDbType.NVarChar)
            command.Parameters.Add("@pos4", SqlDbType.NVarChar)
            command.Parameters.Add("@status", SqlDbType.NVarChar)
            command.Parameters.Add("@type_", SqlDbType.NVarChar)
            command.Parameters.Add("@provider", SqlDbType.NVarChar)
            connection.Open()
            command.Connection = connection

            'If cbCompany.SelectedIndex = 0 Then
            '    company = "KR"
            'ElseIf cbCompany.SelectedIndex = 1 Then
            '    company = "SBC"
            'ElseIf cbCompany.SelectedIndex = 2 Then
            '    company = "KG"
            'End If


            If cbtype.SelectedIndex = 0 Then
                Type = "AlohaQS"
            Else
                Type = "AlohaTS"
            End If

            command.Parameters("@company").Value = cbCompany.SelectedValue.ToString
            command.Parameters("@storenumber").Value = txtStoreno.Text
            command.Parameters("@storename").Value = txtStorename.Text
            command.Parameters("@gateway").Value = txtgateway.Text
            command.Parameters("@serverip").Value = txtserver.Text
            command.Parameters("@mws").Value = txtmws.Text
            command.Parameters("@biometrics").Value = txtbio.Text
            command.Parameters("@pos1").Value = txtpos1.Text
            command.Parameters("@pos2").Value = txtpos2.Text
            command.Parameters("@pos3").Value = txtpos3.Text
            command.Parameters("@pos4").Value = ""
            command.Parameters("@status").Value = ""
            command.Parameters("@type_").Value = Type
            command.Parameters("@provider").Value = txtprovider.Text
            command.ExecuteNonQuery()

            'Manually Apply Changes
            'Find the Key
            For Each items As DataGridViewRow In DataGridView1.Rows
                If items.Cells("p_key").Value() = key Then
                    items.Cells("company").Value() = cbCompany.SelectedValue.ToString
                    items.Cells("storename").Value() = txtStorename.Text
                    items.Cells("type_").Value() = Type
                    items.Cells("serverip").Value() = txtserver.Text
                    items.Cells("mws").Value() = txtmws.Text
                    items.Cells("pos1").Value() = txtpos1.Text
                    items.Cells("pos2").Value() = txtpos2.Text
                    items.Cells("biometrics").Value() = txtbio.Text
                    items.Cells("storenumber").Value() = txtStoreno.Text
                    items.Cells("gateway").Value() = txtgateway.Text
                    items.Cells("pos3").Value() = txtpos3.Text
                End If
            Next

            Clear()
            'reload
            Return True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Sub LoadStores(Optional ByVal what As String = "Null")
        DataGridView1.Refresh()
        DataGridView1.DataSource = Nothing
        Dim conn As New SqlClient.SqlConnection
        With conn
            .ConnectionString = My.Settings.DataSource

            .Open()
        End With

        Dim cmd As New SqlClient.SqlCommand
        With cmd
            If what = "Null" Then
                .CommandText = "SELECT [p_key],[company],[storename],[type_],[serverip],[mws],[pos1],[pos2],[pos3],[biometrics],[storenumber],[gateway],[pos3],[provider],[status] FROM [Management_Info_Sys].[dbo].[stores]"
            Else
                .CommandText = "SELECT [p_key],[company],[storename],[type_],[serverip],[mws],[pos1],[pos2],[pos3],[biometrics],[storenumber],[gateway],[pos3],[provider],[status] FROM [Management_Info_Sys].[dbo].[stores] where storename like '%" & what & "%';"
            End If
            .CommandType = CommandType.Text
            .CommandTimeout = 60
            .Connection = conn
        End With
        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)

        With DataGridView1
            .AutoGenerateColumns = True
            .DataSource = dt
        End With

        For Each item As DataGridViewTextBoxColumn In DataGridView1.Columns
            If item.HeaderText = "company" Then
                item.HeaderText = "Company"
            ElseIf item.HeaderText = "storename" Then
                item.HeaderText = "Store"
            ElseIf item.HeaderText = "type_" Then
                item.HeaderText = "Type"
            ElseIf item.HeaderText = "serverip" Then
                item.HeaderText = "Server IP"
            ElseIf item.HeaderText = "mws" Then
                item.HeaderText = "MWS"
            ElseIf item.HeaderText = "pos1" Then
                item.HeaderText = "POS 1"
            ElseIf item.HeaderText = "pos2" Then
                item.HeaderText = "POS 2"
            ElseIf item.HeaderText = "pos3" Then
                item.HeaderText = "POS 3"
            ElseIf item.HeaderText = "biometrics" Then
                item.HeaderText = "Biometrics"
            ElseIf item.HeaderText = "provider" Then
                item.HeaderText = "Provider"
            ElseIf item.HeaderText = "status" Then
                item.HeaderText = "Status"
            Else
                item.Visible = False
            End If

        Next

        cmd.Dispose()
        cmd = Nothing
        conn.Dispose()
        conn = Nothing

        DataGridView1.Sort(DataGridView1.Columns("company"), System.ComponentModel.ListSortDirection.Ascending)

        Dim t As New Threading.Thread(AddressOf ping)
        t.Start()
    End Sub

#End Region
#Region "Misc"
    Sub Clear()
        txtStoreno.Text = ""
        txtStorename.Text = ""
        txtgateway.Text = ""
        txtserver.Text = ""
        txtmws.Text = ""
        txtpos1.Text = ""
        txtpos2.Text = ""
        txtpos3.Text = ""
        txtbio.Text = ""
        txtprovider.Text = ""
        EditMode = False
    End Sub
    Sub ping()
        For Each items As DataGridViewRow In DataGridView1.Rows
            Try
                'MsgBox(items.Cells(4).Value)
                If subping(items.Cells(4).Value) = True Then

                    items.Cells(4).Style.ForeColor = Color.Green
                End If
                If subping(items.Cells(5).Value) = True Then
                    items.Cells(5).Style.ForeColor = Color.Green
                End If
                If subping(items.Cells(6).Value) = True Then
                    items.Cells(6).Style.ForeColor = Color.Green
                End If
                If subping(items.Cells(7).Value) = True Then
                    items.Cells(7).Style.ForeColor = Color.Green
                End If
                If subping(items.Cells(8).Value) = True Then
                    items.Cells(8).Style.ForeColor = Color.Green
                End If
            Catch ex As Exception
                'MsgBox(ex.Message)
            End Try
        Next
    End Sub

    Function subping(ip As String) As Boolean
        Try
            Dim dom As String = ip

            If InStr(dom, ":") Then
                Dim spliter As String()
                spliter = Split(dom, ":")
                dom = spliter(0)
            End If

            Dim yPing As New Ping
            Dim yPingReply As PingReply
            yPingReply = yPing.Send(dom)
            Dim return_ As String = yPingReply.Status.ToString

            'items.Cells(11).Value = return_

            If return_ = "Succeess" Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function




    Sub LogStatusBar(Label As String, progressstyle As ProgressBarStyle, value As Integer)
        Mainform.ToolStripStatusLabel1.Text = Label
        Mainform.ToolStripProgressBar1.Value = value
        Mainform.ToolStripProgressBar1.Style = progressstyle
    End Sub
    Sub appentlogs(Message As String)
        Message = Message.Trim
        txtlogs.Text = Now.ToString & ": " & Message & vbCrLf & txtlogs.Text
        ' txtlogs.AppendText(Now.ToString & ": " & Message & vbCrLf)
    End Sub

    Sub OpenSharedFolder()

        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows

                Dim loc As String
                loc = "explorer.exe \\" & selecteditems.Cells(4).Value & "\"
                appentlogs(selecteditems.Cells(2).Value & " [" & selecteditems.Cells(4).Value & "] Opening Shared Folder...")
                Shell(loc, AppWinStyle.NormalFocus)
            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try
    End Sub
#End Region
#Region "FileSender"
    Sub EditEcomhook()
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows

                Dim ecomloc As String
                ecomloc = "\\" & selecteditems.Cells(4).Value & "\BOOTDRV\" & selecteditems.Cells(3).Value
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Looking for ecomhook...")
                Dim EcomFullname As String
                EcomFullname = ecomloc & My.Resources.Ecomhook

                Dim ecomhook As New FileInfo(EcomFullname)

                Dim ecomhookstream As StreamReader
                ecomhookstream = ecomhook.OpenText
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Opening ecomhook...")
                Dim ecomhooktext As String = ecomhookstream.ReadToEnd
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Reading ecomhook...")
                Dim Dialog As New ecomhookdialog
                Dialog.TextBox1.Text = ecomhooktext
                Dialog.ShowDialog()
                ecomhookstream.Close()

                If Dialog.DialogResult = DialogResult.OK Then
                    Dim NewHook As String
                    NewHook = Dialog.TextBox1.Text

                    Using writer As StreamWriter = New StreamWriter(ecomhook.FullName)
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Writing Changes ecomhook...")
                        writer.WriteLine(NewHook)
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Writing Changes Done.")
                        writer.Close()
                    End Using
                End If
            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try
    End Sub
    Sub EditFileSenderSettings()
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows

                Dim location As String
                location = "\\" & selecteditems.Cells(4).Value & "\AutoDatedFolderIPVPN\Package\"
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Looking for FileSender Settings...")
                Dim Fullname As String
                Fullname = location & "settings.xml"

                Dim SelectedFile As New FileInfo(Fullname)

                Dim FileStream As StreamReader
                FileStream = SelectedFile.OpenText
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Opening FileSender Settings...")
                Dim ecomhooktext As String = FileStream.ReadToEnd
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Reading FileSender Settings...")
                Dim Dialog As New ecomhookdialog
                Dialog.TextBox1.Text = ecomhooktext
                Dialog.ShowDialog()
                FileStream.Close()

                If Dialog.DialogResult = DialogResult.OK Then
                    Dim NewHook As String
                    NewHook = Dialog.TextBox1.Text

                    Using writer As StreamWriter = New StreamWriter(SelectedFile.FullName)
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Writing Changes FileSender Settings...")
                        writer.WriteLine(NewHook)
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Writing Changes Done.")
                        writer.Close()
                    End Using
                End If
            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try
    End Sub
    Sub ViewFileSenderLogs()

        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows

                Dim ecomloc As String
                ecomloc = "\\" & selecteditems.Cells(4).Value & "\AutoDatedFolderIPVPN\Package\"
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Looking for File Sender Logs...")
                Dim EcomFullname As String
                EcomFullname = ecomloc & "logs.txt"

                Dim ecomhook As New FileInfo(EcomFullname)

                Dim ecomhookstream As StreamReader
                ecomhookstream = ecomhook.OpenText
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Opening File Sender Logs...")
                Dim ecomhooktext As String = ecomhookstream.ReadToEnd
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Reading File Sender Logs...")
                ecomhookstream.Close()
                Dim Dialog As New ecomhookdialog
                Dialog.TextBox1.Text = ecomhooktext
                Dialog.ShowDialog()

            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try

    End Sub
    Sub UpdatedFileSender(Filename As String)
        ' appentlogs("Selecting FileSender..")
        'MsgBox(Filename)
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Dim FileSenderParent As String
                FileSenderParent = "\\" & selecteditems.Cells(4).Value & "\AutoDatedFolderIPVPN\Package\"
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Looking for File Sender Logs...")
                Dim FileSenderFullname As String
                FileSenderFullname = FileSenderParent & "FileSender.exe"

                Dim StoreVersion As Version
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Getting File Version...")
                StoreVersion = GetFileVersionInfo(FileSenderFullname)
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Store File Version [" & StoreVersion.ToString & "]")

                Dim NewVersion As Version
                appentlogs("HeadOffice" & " " & " Getting File Version...")
                NewVersion = GetFileVersionInfo(Filename)
                appentlogs("HeadOffice" & " " & " New File Version [" & NewVersion.ToString & "]")
                If NewVersion > StoreVersion Then
                    appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Updating...")
                    Try
                        If File.Exists(FileSenderFullname) Then
                            File.Delete(FileSenderFullname)
                        End If
                        File.Copy(Filename, FileSenderFullname, True)
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Update Success")
                    Catch ex As Exception
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Update Failed because " & ex.Message)
                    End Try
                Else
                    appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Already Up-to-Date")
                End If
            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try
    End Sub
    Sub UpdatedAllFileSender(Filename As String)
        ' appentlogs("Selecting FileSender..")
        'MsgBox(Filename)
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.Rows
                Dim FileSenderParent As String
                FileSenderParent = "\\" & selecteditems.Cells(4).Value & "\AutoDatedFolderIPVPN\Package\"
                appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Looking for File Sender...")
                Dim FileSenderFullname As String
                FileSenderFullname = FileSenderParent & "FileSender.exe"
                If File.Exists(FileSenderFullname) = True Then
                    Dim StoreVersion As Version
                    appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Getting File Version...")
                    StoreVersion = GetFileVersionInfo(FileSenderFullname)
                    appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Store File Version [" & StoreVersion.ToString & "]")

                    Dim NewVersion As Version
                    appentlogs("HeadOffice" & " " & " Getting File Version...")
                    NewVersion = GetFileVersionInfo(Filename)
                    appentlogs("HeadOffice" & " " & " New File Version [" & NewVersion.ToString & "]")
                    If NewVersion > StoreVersion Then
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Updating...")
                        Try
                            If File.Exists(FileSenderFullname) Then
                                File.Delete(FileSenderFullname)
                            End If
                            File.Copy(Filename, FileSenderFullname, True)
                            appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Update Success")
                        Catch ex As Exception
                            appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Update Failed because " & ex.Message)
                        End Try
                    Else
                        appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " Already Up-to-Date")
                    End If
                Else
                    appentlogs(selecteditems.Cells(1).Value & " " & selecteditems.Cells(2).Value & " No Connection or File Not Found")
                End If
            Next
            appentlogs("Done")
        Catch ex As Exception
            appentlogs(ex.Message)
        End Try
    End Sub
    Private Function GetFileVersionInfo(ByVal filename As String) As Version
        Return Version.Parse(FileVersionInfo.GetVersionInfo(filename).FileVersion)
    End Function
#End Region
    Dim MyLib As New Class1
    Private Sub storecontrol_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
        cbCompany.SelectedIndex = 0
        cbtype.SelectedIndex = 0
        MyLib.LoadStores(DataGridView1)
        LoadCompany()

        Dim t As New Threading.Thread(AddressOf ping)
        t.Start()
    End Sub
    Dim company As String
    Dim Type As String
    Dim EditMode As Boolean
    Dim PrimaryKey As String = ""
    Public Mainform As Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'Send Edited


        If txtStoreno.Text = "" Then
            MsgBox("Store Number must set", MsgBoxStyle.Critical, "Null Values")
            txtStoreno.Focus()
            Return
        End If
        If txtStorename.Text = "" Then
            MsgBox("Store Name must set", MsgBoxStyle.Critical, "Null Values")
            txtStorename.Focus()
            Return
        End If
        If txtgateway.Text = "" Then
            MsgBox("Gateway must set", MsgBoxStyle.Critical, "Null Values")
            txtgateway.Focus()
            Return
        End If
        If txtserver.Text = "" Then
            MsgBox("Server must set", MsgBoxStyle.Critical, "Null Values")
            txtserver.Focus()
            Return
        End If
        If txtmws.Text = "" Then
            MsgBox("MWS must set", MsgBoxStyle.Critical, "Null Values")
            txtmws.Focus()
            Return
        End If
        If txtpos1.Text = "" Then
            MsgBox("POS1 must set", MsgBoxStyle.Critical, "Null Values")
            txtpos1.Focus()
            Return
        End If
        'Save
      
        company = cbCompany.SelectedValue.ToString
        Type = cbtype.SelectedItem.ToString

        If EditMode = True Then
            Edit(PrimaryKey)
        Else
            Add()
        End If

        'Clear
        Clear()
    End Sub

#Region "ContextMenu"
    Private Sub ServerToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ServerToolStripMenuItem.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "C:\Program Files\RealVNC\VNC4\vncviewer.exe"
                Process1.StartInfo.Arguments = " " & selecteditems.Cells(4).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub MWSToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MWSToolStripMenuItem.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "C:\Program Files\RealVNC\VNC4\vncviewer.exe"
                Process1.StartInfo.Arguments = " " & selecteditems.Cells(5).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub POS1ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles POS1ToolStripMenuItem.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "C:\Program Files\RealVNC\VNC4\vncviewer.exe"
                Process1.StartInfo.Arguments = " " & selecteditems.Cells(6).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub POS2ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles POS2ToolStripMenuItem.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "C:\Program Files\RealVNC\VNC4\vncviewer.exe"
                Process1.StartInfo.Arguments = " " & selecteditems.Cells(7).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub EditToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditToolStripMenuItem.Click
        Try
            EditMode = True
            'Load data
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                PrimaryKey = selecteditems.Cells("p_key").Value
                'MsgBox(PrimaryKey)
                cbCompany.SelectedValue = selecteditems.Cells("company").Value
                cbtype.SelectedItem = selecteditems.Cells("type_").Value
                'If selecteditems.Cells("type_").Value = "AlohaQS" Then
                '    cbtype.SelectedIndex = 0
                'ElseIf selecteditems.Cells("type_").Value = "AlohaTS" Then
                '    cbtype.SelectedIndex = 1
                'Else
                '    cbtype.SelectedIndex = 2
                'End If

                txtStoreno.Text = selecteditems.Cells("storenumber").Value
                txtStorename.Text = selecteditems.Cells("storename").Value
                txtgateway.Text = selecteditems.Cells("gateway").Value
                txtserver.Text = selecteditems.Cells("serverip").Value
                txtmws.Text = selecteditems.Cells("mws").Value
                txtpos1.Text = selecteditems.Cells("pos1").Value
                txtpos2.Text = selecteditems.Cells("pos2").Value
                txtpos3.Text = selecteditems.Cells("pos3").Value
                txtbio.Text = selecteditems.Cells("biometrics").Value

            Next

            TabControl1.SelectedTab = TabPage1
            txtStoreno.Focus()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub LoadCompany()
        Dim conn As New SqlClient.SqlConnection
        With conn
            .ConnectionString = My.Settings.DataSource
            .Open()
        End With

        Dim cmd As New SqlClient.SqlCommand
        With cmd
            .CommandText = "SELECT [Company] FROM [Management_Info_Sys].[dbo].[company];"
            .CommandType = CommandType.Text
            .CommandTimeout = 60
            .Connection = conn
        End With
        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)

        cbCompany.ValueMember = "Company"
        cbCompany.DisplayMember = "Company"
        cbCompany.DataSource = dt
        'With DataGridGroup
        '    .AutoGenerateColumns = True
        '    .DataSource = dt
        'End With



    End Sub
    Private Sub RefreshToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RefreshToolStripMenuItem.Click
        DataGridView1.Refresh()
        DataGridView1.DataSource = Nothing
        MyLib.LoadStores(DataGridView1)
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim t As New Threading.Thread(AddressOf ping)
        t.Start()
    End Sub

    Private Sub ServerToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ServerToolStripMenuItem1.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "mstsc"
                Process1.StartInfo.Arguments = " /v:" & selecteditems.Cells(4).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Private Sub MWSToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles MWSToolStripMenuItem1.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
                Process1.StartInfo.FileName = "mstsc"
                Process1.StartInfo.Arguments = " /v:" & selecteditems.Cells(5).Value
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                Process1.Start()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub NetsalesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NetsalesToolStripMenuItem.Click
        Dim netdialog As New ReportDialog

        For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
            netdialog.ServerIP = selecteditems.Cells(4).Value
            netdialog.storetype = selecteditems.Cells(3).Value
            netdialog.StoreName = selecteditems.Cells(2).Value
            netdialog.Show()
        Next

    End Sub

    Private Sub ArchiveDatedFoldersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ArchiveDatedFoldersToolStripMenuItem.Click

    End Sub

    Private Sub GroupBox1_Enter(sender As Object, e As EventArgs) Handles GroupBox1.Enter

    End Sub

    Private Sub SearchToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchToolStripMenuItem.Click
        Dim What As String = "null"
        What = InputBox("Find Store", "Find")
        If What <> "null" Then
            'LoadStores(What)
            'MyLib.LoadStores(DataGridView1)
            MyLib.LoadStores(DataGridView1, What)
        End If
    End Sub

    Private Sub EditWinhookScriptToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditWinhookScriptToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf EditEcomhook)
        t.Start()
    End Sub

    Private Sub ViewLogsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewLogsToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf ViewFileSenderLogs)
        t.Start()
    End Sub

    Private Sub OpenSharedFolderToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenSharedFolderToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf OpenSharedFolder)
        t.Start()
    End Sub

    Private Sub UpdateFileSenderToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UpdateFileSenderToolStripMenuItem.Click
        Dim OpenFile As New OpenFileDialog
        OpenFile.Multiselect = False
        OpenFile.RestoreDirectory = True
        OpenFile.Filter = "FileSender Exe (*.exe)|*.exe|All files (*.*)|*.*"

        If OpenFile.ShowDialog() = DialogResult.OK Then
            Dim t As New Threading.Thread(AddressOf UpdatedFileSender)
            t.Start(OpenFile.FileName.ToString())
        End If

    End Sub

    Private Sub UpdateAllFileSenderToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UpdateAllFileSenderToolStripMenuItem.Click
        Dim a = MsgBox("Are you sure you want to update all File Sender?", vbYesNo, "Update All")
        If a = MsgBoxResult.Yes Then
            Dim OpenFile As New OpenFileDialog
            OpenFile.Multiselect = False
            OpenFile.RestoreDirectory = True
            OpenFile.Filter = "FileSender Exe (*.exe)|*.exe|All files (*.*)|*.*"

            If OpenFile.ShowDialog() = DialogResult.OK Then
                Dim t As New Threading.Thread(AddressOf UpdatedAllFileSender)
                t.Start(OpenFile.FileName.ToString())
            End If
        End If
    End Sub
#End Region

    Sub FinalPing(CellStore As String, CellDescription As String, CellTarget As String)
        PingTimer.Enabled = False
        PingDom = CellTarget
        Try
            If InStr(PingDom, ":") Then
                Dim spliter As String()
                spliter = Split(PingDom, ":")
                Pingport = spliter(1)
                PingDom = spliter(0)
            End If
            
            appentlogs("Pinging Hostname = " & CellStore & " Description = """ & CellDescription & """ IP = " & CellTarget)

            PingTimer.Enabled = True
        Catch ex As Exception
            appentlogs("GENERAL FAILURE")
             End Try
    End Sub
    Dim PingDom As String
    Dim Pingport As Integer
    Dim vPing As New Ping
    Dim vPingReply As PingReply

    Private Sub ServerToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles ServerToolStripMenuItem2.Click
        For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
            FinalPing(selecteditems.Cells(2).Value, "Server", selecteditems.Cells(4).Value)
        Next
    End Sub

    Private Sub MWSToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles MWSToolStripMenuItem2.Click
        For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
            FinalPing(selecteditems.Cells(2).Value, "MWS", selecteditems.Cells(5).Value)
        Next
    End Sub

    Private Sub POS1ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles POS1ToolStripMenuItem1.Click
        For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
            FinalPing(selecteditems.Cells(2).Value, "POS 1", selecteditems.Cells(6).Value)
        Next
    End Sub

    Private Sub POS2ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles POS2ToolStripMenuItem1.Click
        For Each selecteditems As DataGridViewRow In DataGridView1.SelectedRows
            FinalPing(selecteditems.Cells(2).Value, "POS 2", selecteditems.Cells(7).Value)
        Next
    End Sub
    Dim PingTimerCounter As Integer = 0
    Dim PingLimit As Integer = 20
    Dim PingThreadList As New ArrayList
    Private Sub PingTimer_Tick(sender As Object, e As EventArgs) Handles PingTimer.Tick
        PingTimerCounter += 1
        If PingTimerCounter >= PingLimit Then
            PingTimer.Enabled = False
            PingTimerCounter = 0
            Try
                appentlogs("Ping Done to " & vPingReply.Address.ToString & ": with status=" & vPingReply.Status.ToString)
            Catch ex As Exception
                appentlogs("Ping Done to " & PingDom & ": with status=Cannot Connect")
            End Try
            
        Else
            Dim t As New Threading.Thread(AddressOf PingThread)
            PingThreadList.Add(t)
            t.Start()
        End If
        ' MsgBox(PingReply1.Status)


    End Sub
    Sub PingThread()
        Try
            vPingReply = vPing.Send(PingDom)
            If vPingReply.Status.ToString <> "Success" Then
                appentlogs("Reply from " & vPingReply.Address.ToString & ": " & vPingReply.Status.ToString)
            Else
                appentlogs("Reply from " & vPingReply.Address.ToString & ": " & "time=" & vPingReply.RoundtripTime() & "ms TTL=" & vPingReply.Options.Ttl)
            End If
        Catch ex As Exception
            appentlogs("Request Time Out")
        End Try
    End Sub

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        
    End Sub

    Private Sub EditSettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditSettingsToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf EditFileSenderSettings)
        t.Start()
    End Sub
End Class
